//
//  SEPatientDetailViewController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/15.
//

import UIKit

enum SEPatientDetailViewControllerEditType {
    case add
    case edit
}

class SEPatientDetailViewController: SEBaseViewController {

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.tableFooterView = tableFooterView
            tableView.rowHeight = 50
            tableView.separatorColor = UIColor.init(hex: "EBECF0")
            tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            tableView.keyboardDismissMode = .onDrag
            tableView.register(UINib(nibName: SEPatientTitleTextFieldCell.className, bundle: nil), forCellReuseIdentifier: SEPatientTitleTextFieldCell.reuseId)
        }
    }

    var viewModel = SEPatientDetailViewModel()
    var submitSuccessHandler: (() -> Void)?

    init(with viewModel: SEPatientDetailViewModel, editType: SEPatientDetailViewControllerEditType) {
        viewModel.editType = editType
        if editType == .edit {
            self.viewModel = viewModel
        }
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if viewModel.editType == .edit {
            title = "编辑就诊人"
            requestPatientDetail()
        } else {
            title = "添加就诊人"
            tableView.isHidden = false
        }
        // Do any additional setup after loading the view.
    }

    override func setupUI() {
        super.setupUI()

        viewModel.updateData = { status in
            switch status {
            case .success:
                self.tableView.isHidden = false
                self.tableView.reloadData()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestPatientDetail)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.submitHandler = { status in
            switch status {
            case .success:
                SEHUD.show(message: "提交成功")
                self.submitSuccessHandler?()
                self.navigationController?.popViewController(animated: true)
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.submitPatientDetail)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.msgCodeHandler = { status in
            switch status {
            case .success:
                let cell = self.tableView.cellForRow(at: IndexPath(row: 5, section: 0)) as! SEPatientTitleTextFieldCell
                cell.fireTimer()
                SEHUD.show(message: "验证码发送成功")
            case .auth(let msg), .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    lazy var headerView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.background
        let label = UILabel()
        label.text = "健康档案（以下非必填）"
        label.textColor = Asset.textDark.color
        label.font = UIFont.regular(13)
        view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerY.equalTo(view.snp.centerY)
        }
        return view
    }()

    private lazy var tableFooterView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: 30 + 48 + 25))
        let btnView = SERegistrationConfirmBtnView(frame: CGRect(x: 15, y: 30, width: UIScreen.screenWidth - 30, height: 48))
        btnView.delegate = self
        btnView.title = "保存"
        view.addSubview(btnView)
        return view
    }()

    private func tableFooterTextView(placeHolder: String, text: String, tag: Int) -> UIView {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: 105))
        view.backgroundColor = UIColor.white
        let textView = SETextView()
        textView.tag = tag
        textView.font = UIFont.systemFont(ofSize: 15)
        textView.frame = CGRect(x: 15, y: 0, width: UIScreen.screenWidth - 30, height: 90)
        textView.layer.cornerRadius = 4
        textView.layer.borderWidth = 1
        textView.layer.borderColor = Asset.border.color.cgColor
        textView.layer.masksToBounds = true
        textView.placeholder = placeHolder
        textView.text = text
        textView.tvDelegate = self
        view.addSubview(textView)
        return view
    }

}

// MARK: - UITableViewDataSource, UITableViewDelegate

extension SEPatientDetailViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard section < viewModel.dataSource.count else {
            return 0
        }
        return viewModel.dataSource[section].count
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.dataSource.count + 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEPatientTitleTextFieldCell.reuseId, for: indexPath) as! SEPatientTitleTextFieldCell
        cell.delegate = self
        cell.updateCell(model: viewModel.dataSource[indexPath.section][indexPath.row], indexPath: indexPath)
        return cell
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 {
            return headerView
        } else {
            var placeHolder = ""
            var text = ""
            var tag = 0
            if section == 2 {
                tag = 100
                placeHolder = "描述您的过敏史（包括药物和食物过敏史）"
                text = viewModel.model.allergyHistory
            }
            if section == 3 {
                tag = 101
                placeHolder = "描述您的既往史（既往的健康状况和过去曾经患过的疾病等方面的问题，既往健康状况包括饮食习惯等）"
                text = viewModel.model.diagnoseHistory
            }
            return tableFooterTextView(placeHolder: placeHolder, text: text, tag: tag)
        }
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 1: return 42
        case 2: return viewModel.model.isAllergy == 0 ? 0 : 105
        case 3: return 105
        default: return 0
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = viewModel.dataSource[indexPath.section][indexPath.row]
        if !model.editEnable {
            view.endEditing(true)
            SEHUD.showError(message: "\(model.title)不支持修改")
        }
    }

}

// MARK: - SERegistrationConfirmBtnViewDelegate

extension SEPatientDetailViewController: SERegistrationConfirmBtnViewDelegate {
    func registrationConfirmBtnViewAction(view: SERegistrationConfirmBtnView) {
        self.view.endEditing(true)
        submitPatientDetail()
    }
}

// MARK: SEPatientTitleTextFieldCellDelegate

extension SEPatientDetailViewController: SEPatientTitleTextFieldCellDelegate {
    func patientTitleTextFieldCellCodeBtnAction() {
        view.endEditing(true)
        viewModel.requestMsgCode()
    }

    func patientTitleTextFieldCellDidEndEdit(titleTextFieldCell: SEPatientTitleTextFieldCell, indexPath: IndexPath) {
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                viewModel.model.name = titleTextFieldCell.textField.text!
            case 1:
                viewModel.model.idNumber = titleTextFieldCell.textField.text!
            case 2:
                presentAddressController()
            case 3:
                viewModel.model.addr = titleTextFieldCell.textField.text!
            case 4:
                viewModel.model.phone = titleTextFieldCell.textField.text!
                viewModel.authViewModel.account = titleTextFieldCell.textField.text!
            case 5:
                viewModel.model.msgCode = titleTextFieldCell.textField.text!
            case 6:
                showCommonPickerView()
            default:
                print("\(indexPath.section),\(indexPath.row)")
            }
        case 1:
            switch indexPath.row {
            case 0:
                viewModel.model.height = titleTextFieldCell.textField.text!
            case 1:
                viewModel.model.weight = titleTextFieldCell.textField.text!
            case 2:
                viewModel.model.isSmoking = titleTextFieldCell.segmentControl.selectedSegmentIndex
            case 3:
                viewModel.model.isDrinking = titleTextFieldCell.segmentControl.selectedSegmentIndex
            case 4:
                viewModel.model.isAllergy = titleTextFieldCell.segmentControl.selectedSegmentIndex == 0 ? 1 : 0
                tableView.reloadData {
                    if self.viewModel.model.isAllergy == 0 {
                        self.view.endEditing(true)
                    }
                }
            default:
                print("\(indexPath.section),\(indexPath.row)")
            }
        default:
            print("\(indexPath.section),\(indexPath.row)")
        }
    }

    private func presentAddressController() {
        view.endEditing(true)
        let addressVc = AddressViewController()
        addressVc.modalPresentationStyle = .custom
        addressVc.chooseClosure = { model in
            self.viewModel.model.province = model.provinceId
            self.viewModel.model.provinceName = model.provinceName
            self.viewModel.model.city = model.cityId
            self.viewModel.model.cityName = model.cityName
            self.viewModel.model.region = model.areaId
            self.viewModel.model.regionName = model.areaName
            self.tableView.reloadData()
        }
        present(addressVc, animated: true) {
            addressVc.view.backgroundColor = UIColor.black.withAlphaComponent(0.36)
        }
    }

    private func showCommonPickerView() {
        view.endEditing(true)
        let picker = UINib.loadViewFrom(CommonPickerView.self)
        picker.frame = CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: UIScreen.screenHeight)
        picker.show(type: .relation)
        picker.selectedClosure = { model in
            self.viewModel.model.relation = model.code.intValue
            self.tableView.reloadData()
        }
    }
}

// MARK: - SETextViewDelegate

extension SEPatientDetailViewController: SETextViewDelegate {
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.tag == 100 {
            viewModel.model.allergyHistory = textView.text
        }
        if textView.tag == 101 {
            viewModel.model.diagnoseHistory = textView.text
        }
    }
}

// MARK: - APIRequest

extension SEPatientDetailViewController{
    @objc private func requestPatientDetail() {
        viewModel.requestPatientDetail()
    }

    @objc private func submitPatientDetail() {
        viewModel.submitPatientDetail()
    }
}

